# -*- coding: utf-8 -*-
# Project  : rabbitmq_demo
# FileName : cousumer.py
# Time     : 2021/1/14 14:10
# Author  : Mason101

# 生产者，采用关键字模式

import pika


class DirectConsumer:
    def __init__(self):
        self.host = "127.0.0.1"
        self.port = 5672
        self.username = "guest"
        self.password = "guest"
        self.queue_name = None
        self.connection = self.create_connection()
        self.channel = self.create_channel()

    def create_connection(self):
        credentials = pika.PlainCredentials(self.username, self.password, True)
        connection = pika.BlockingConnection(pika.ConnectionParameters(self.host, self.port, "/", credentials))
        print(connection)
        return connection

    # 声明管道，绑定管道、交换机
    def create_channel(self):
        # 声明管道
        channel = self.connection.channel()
        channel.exchange_declare(exchange="python-test", exchange_type="direct", durable=True)

        # 创建临时队列
        res = channel.queue_declare(queue='queue-test', durable=True)
        self.queue_name = res.method.queue
        channel.queue_bind(exchange="python-test", queue=res.method.queue, routing_key="id")

        return channel

    # 定义回调函数处理接受到的数据
    def callback(self, ch, method, properties, body):
        print(f"recv data: {body}")

        ch.basic_ack(delivery_tag=method.delivery_tag)

    # 接收数据
    def recv_data(self):
        self.channel.basic_consume(queue=self.queue_name, auto_ack=False, on_message_callback=self.callback)

        print("wait message ....")
        self.channel.start_consuming()


if __name__ == '__main__':
    consumer_obj = DirectConsumer()
    consumer_obj.recv_data()






